import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_date_picker/flutter_cupertino_date_picker.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_easyrefresh/material_header.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_picker/Picker.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:panda/base/SignType.dart';
import 'package:panda/entity/common_entity.dart';
import 'package:panda/entity/order_list_entity.dart';
import 'package:panda/entity/order_list_entity3.dart';
import 'package:panda/home/MyBottomBar2.dart';
import 'package:panda/http/Api.dart';
import 'package:panda/http/HttpUtil.dart';
import 'package:panda/order/MyHomePage.dart';
import 'package:panda/util/AppSaveInfoUtil.dart';
import 'package:panda/util/DateUtils.dart';
import 'package:panda/util/LoadingUtil.dart';
import 'package:panda/util/SignUtil.dart';
import 'package:popup_window/popup_window.dart';

import '../base/Constant.dart';

class ShouRuChildPage extends StatefulWidget {
  var type;
  ShouRuChildPage({Key key, @required this.type}) : super(key: key);
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return AllOrderView();
  }
}

class AllOrderView extends State<ShouRuChildPage>
    with AutomaticKeepAliveClientMixin, WidgetsBindingObserver {
  List<OrderList3DataData> dataList = List();
  // List<CommonEntityDataData> logs = new List();
  int page = 1;
  EasyRefreshController _controller = new EasyRefreshController();
  String token = "";
  var PickerData = [], allPrice = "0";
  String bank_id = "", name = "选择快递", time1 = "";
  String backReason = "", backReason2 = "", danhao = "", order_num = "";
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    var today = DateTime.now();
    time1 = DateUtils.instance.getFormartData(
        timeSamp: today.millisecondsSinceEpoch, format: "yyyy-MM-dd");
    // time2 = time1;
    getString(TOKEN).then((value) {
      token = value;
      if (token == null) {
        return;
      }
      loadList();
    });
    // loadListLog();
  }

  // loadListLog() async {
  //   Map map = new Map();
  //   Response<String> response =
  //       await HttpUtil().post(Api.GET_LOGINS, data: getSign(map));
  //   Map userMap = json.decode(response.data);
  //   if (userMap['code'] != 1) {
  //     Fluttertoast.showToast(msg: userMap['msg']);
  //     return;
  //   }
  //   CommonEntityEntity homeListEntity =
  //       new CommonEntityEntity.fromJson(userMap);
  //   if (mounted)
  //     setState(() {
  //       logs.addAll(homeListEntity.data.datas);
  //       for (int i = 0; i < logs.length; i++) {
  //         PickerData.add("\"" + logs[i].title + "\"");
  //       }
  //     });
  // }

  // var myState1;
  // showCate() {
  //   new Picker(
  //       adapter: PickerDataAdapter<String>(
  //           pickerdata: new JsonDecoder().convert(PickerData.toString())),
  //       hideHeader: true,
  //       title: new Text("选择快递"),
  //       cancelText: "取消",
  //       cancelTextStyle: TextStyle(color: Colors.grey),
  //       confirmText: "确定",
  //       confirmTextStyle: TextStyle(color: mainColor),
  //       onConfirm: (Picker picker, List value) {
  //         bank_id = logs[value[0]].id;
  //         // controller.text = name;
  //         name = picker.getSelectedValues()[0];
  //         myState1(() {});
  //       }).showDialog(context);
  // }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    // TODO: implement didChangeAppLifecycleState
    super.didChangeAppLifecycleState(state);
    if (state == AppLifecycleState.resumed)
      getString(TOKEN).then((value) {
        token = value;
      });
  }

  loadList() async {
    // if (page == 1) {
    //   showDialog(
    //       context: context,
    //       barrierDismissible: false,
    //       builder: (_) {
    //         return new NetLoadingDialog(
    //           loadingText: "查询中...",
    //           bgColor: Color.fromARGB(255, 0, 0, 0),
    //           requestCallBack: null,
    //           outsideDismiss: false,
    //         );
    //       });
    // }
    Map map = new Map();
    map['token'] = token;
    map['type'] = widget.type;
    map['date'] = time1;
    map['p'] = page;
    map['per'] = 10;
    map['sign_type'] = SignType.USER_ORDER_LIST;
    Response<String> response = await HttpUtil().post(
        Api.BaseUrl + "/index.php/wap/User/getTeamOrder_new",
        data: getSign(map));
    Map userMap = json.decode(response.data);
    // if (page == 1) {
    //   Navigator.of(context).pop(1);
    // }
    if (userMap['code'] != 1) {
      Fluttertoast.showToast(msg: userMap['msg']);
      return;
    }
    allPrice = userMap['data']['allprice'].toString();
    OrderList3Entity homeListEntity = new OrderList3Entity.fromJson(userMap);
    if (mounted)
      setState(() {
        if (page == 1) {
          dataList.clear();
          dataList.addAll(homeListEntity.data.datas);
        } else {
          dataList.addAll(homeListEntity.data.datas);
        }
        if (page == 1) {
          _controller.resetLoadState();
          _controller.finishRefresh();
        } else {
          _controller.finishLoad(noMore: homeListEntity.data.datas.length == 0);
          if (homeListEntity.data.datas.length == 0) {
            Fluttertoast.showToast(msg: "暂无更多数据");
          }
        }
      });
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    // TODO: implement build
    return new Container(
      child: new Container(
        color: divideColor,
        child: new Column(
          children: <Widget>[
            Container(
              padding: EdgeInsets.all(10),
              color: white,
              child: Row(
                children: <Widget>[
                  Container(
                    margin: EdgeInsets.only(bottom: 0.5),
                    color: white,
                    alignment: Alignment.centerLeft,
                    child: Text('当前总计:$MONEY' + "$allPrice",
                        style: TextStyle(
                            fontSize: ScreenUtil.getInstance().setSp(26))),
                  ),
                  Expanded(child: Center()),
                  // Text("筛选",
                  //     style: TextStyle(
                  //         color: Colors.grey,
                  //         fontSize: ScreenUtil.getInstance().setSp(26))),
                  // Icon(
                  //   Icons.sort,
                  //   size: 20,
                  //   color: Colors.grey,
                  // ),
                  GestureDetector(
                    child: Container(
                      padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
                      decoration: BoxDecoration(
                          border: Border.all(color: black_99, width: 1),
                          borderRadius: BorderRadius.circular(3)),
                      child: Row(children: <Widget>[
                        Text('$time1',
                            style: TextStyle(
                                color: black_99,
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(SMALL_FONT_SIZE + 3))),
                        Icon(
                          Icons.arrow_drop_down,
                          color: black_99,
                        )
                      ]),
                    ),
                    onTap: () {
                      DatePicker.showDatePicker(context,
                          pickerTheme: DateTimePickerTheme(
                            showTitle: true,
                            confirm:
                                Text('确定', style: TextStyle(color: Colors.red)),
                            cancel: Text('取消',
                                style: TextStyle(color: Colors.cyan)),
                          ),
                          minDateTime: DateTime.parse("1980-05-01"),
                          dateFormat: "yyyy-MM-dd",
                          pickerMode: DateTimePickerMode.date,
                          locale: DateTimePickerLocale.zh_cn, onCancel: () {
                        debugPrint("onCancel");
                      }, onConfirm: (dateTime, List<int> index) {
                        time1 = DateUtils.instance.getFormartData(
                            timeSamp: dateTime.millisecondsSinceEpoch,
                            format: "yyyy-MM-dd");
                        setState(() {});
                        page = 1;
                        loadList();
                      });
                    },
                  ),
                ],
              ),
            ),
            Divider(
              height: 1,
            ),
            Expanded(
                child: new EasyRefresh(
              controller: _controller,
              header: MaterialHeader(),
              footer: MaterialFooter(),
              enableControlFinishLoad: true,
              enableControlFinishRefresh: true,
              child: dataList.length == 0
                  ? Container(
                      alignment: Alignment.center,
                      height: MediaQuery.of(context).size.height / 2,
                      child: Text('暂无订单数据',
                          style: TextStyle(
                              color: mainColor,
                              fontSize: ScreenUtil.getInstance().setSp(35))),
                    )
                  : ListView.separated(
                      itemBuilder: _renderRow,
                      separatorBuilder: (BuildContext context, int index) {
                        return Container(
                          color: divideColor,
                          height: 0,
                        );
                      },
                      itemCount: dataList.length),
              onRefresh: () async {
                page = 1;
                loadList();
              },
              onLoad: () async {
                page++;
                loadList();
              },
            )),
          ],
        ),
      ),
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    return new GestureDetector(
      onTap: () {
        // Navigator.of(context).push(MaterialPageRoute(builder: (context) {
        //   return new OrderDetailPage(
        //     id: dataList[index].id,
        //   );
        // }));
      },
      child: new Container(
        decoration: BoxDecoration(
            color: Colors.white, borderRadius: BorderRadius.circular(0.0)),
        child: new Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            // Offstage(
            //   child: Container(
            //     padding: EdgeInsets.all(10),
            //     width: double.infinity,
            //     color: divideColor,
            //     child: Text(dataList[index].create_time.split(" ")[0],
            //         style: TextStyle(
            //             color: black,
            //             fontSize:
            //                 ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE))),
            //   ),
            //   offstage: index != 0,
            // ),
            Container(
              height: 10,
            ),
            Container(
                padding: EdgeInsets.only(left: 10, right: 10),
                child: Column(
                  children: <Widget>[
                    Padding(
                      padding: EdgeInsets.only(bottom: 9, right: 0),
                      child: Row(
                        children: <Widget>[
                          ClipOval(
                            child: dataList[index].avatar == null ||
                                    dataList[index].avatar == "" ||
                                    dataList[index].avatar == "null"
                                ? Image.asset("images/app_icon.png")
                                : CachedNetworkImage(
                                    imageUrl:
                                        dataList[index].avatar.contains("http")
                                            ? dataList[index].avatar
                                            : Api.ImgBaseUrl +
                                                dataList[index].avatar,
                                    width: ScreenUtil.getInstance()
                                        .setHeight(DP_50),
                                    fit: BoxFit.fill,
                                    height: ScreenUtil.getInstance()
                                        .setHeight(DP_50)),
                          ),
                          // Text("   " + dataList[index].nickname,
                          //     style: TextStyle(
                          //         fontSize: ScreenUtil.getInstance()
                          //             .setSp(SMALL_FONT_SIZE + 2))),
                          // Expanded(
                          //   child: Text(" " + dataList[index].group_name,
                          //       style: TextStyle(
                          //           fontSize: ScreenUtil.getInstance()
                          //               .setSp(SMALL_FONT_SIZE - 2))),
                          // ),
                          Container(
                            width: 8,
                          ),
                          Expanded(
                              child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              new Text(
                                dataList[index].nickname +
                                    "  会员ID:" +
                                    dataList[index].user_id,
                                style: new TextStyle(
                                    color: Colors.black,
                                    fontSize:
                                        ScreenUtil.getInstance().setSp(24)),
                              ),
                              // new Text(
                              //   '所属店铺:  ' + dataList[index].reffeer_name,
                              //   style: new TextStyle(
                              //       color: Colors.black54,
                              //       fontSize:
                              //           ScreenUtil.getInstance().setSp(24)),
                              // ),
                            ],
                          )),
                          Text(dataList[index].status_zh,
                              style: TextStyle(
                                  color: mainColor,
                                  fontSize: ScreenUtil.getInstance()
                                      .setSp(NORMAL_FONT_SIZE - 3)))
                        ],
                      ),
                    ),
                    Divider(height: 1),
                    Container(height: 10),
                    Row(
                      children: <Widget>[
                        ClipRRect(
                          borderRadius: BorderRadius.circular(2),
                          child: dataList[index].img == "" ||
                                  dataList[index].img == null ||
                                  dataList[index].img == "null"
                              ? Center()
                              : CachedNetworkImage(
                                  imageUrl:
                                      Api.ImgBaseUrl + dataList[index].img,
                                  width: ScreenUtil.getInstance()
                                      .setHeight(DP_120),
                                  fit: BoxFit.fill,
                                  height: ScreenUtil.getInstance()
                                      .setHeight(DP_120)),
                        ),
                        Container(
                          width: 10,
                        ),
                        Expanded(
                          child: Container(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                Padding(
                                  padding: EdgeInsets.only(top: 0, right: 0),
                                  child: Row(
                                    children: <Widget>[
                                      Expanded(
                                        child: Text(
                                            "订单号: " +
                                                dataList[index]
                                                    .order_num
                                                    .toString(),
                                            style: TextStyle(
                                                fontSize:
                                                    ScreenUtil.getInstance()
                                                        .setSp(SMALL_FONT_SIZE +
                                                            1))),
                                      ),
                                    ],
                                  ),
                                ),
                                Container(
                                  height: 5,
                                ),
                                Text(dataList[index].title.toString(),
                                    maxLines: 2,
                                    overflow: TextOverflow.ellipsis,
                                    style: TextStyle(
                                        fontSize: ScreenUtil.getInstance()
                                            .setSp(NORMAL_FONT_SIZE - 3))),
                                Container(
                                  height: 5,
                                ),
                                Row(
                                  children: <Widget>[
                                    Expanded(
                                      child: Text(
                                          "共" +
                                              dataList[index].num.toString() +
                                              "件，合计" +
                                              MONEY +
                                              dataList[index]
                                                  .allprice
                                                  .toString(),
                                          style: TextStyle(
                                              color: Colors.black54,
                                              fontSize: ScreenUtil.getInstance()
                                                  .setSp(
                                                      NORMAL_FONT_SIZE - 4))),
                                    ),
                                    Text("+" + dataList[index].money.toString(),
                                        style: TextStyle(
                                            color: mainColor,
                                            fontSize: ScreenUtil.getInstance()
                                                .setSp(NORMAL_FONT_SIZE))),
                                  ],
                                ),
                                Container(
                                  height: 5,
                                ),
                                Text(dataList[index].create_time,
                                    style: TextStyle(
                                        color: Colors.black54,
                                        fontSize: ScreenUtil.getInstance()
                                            .setSp(NORMAL_FONT_SIZE - 4)))
                              ],
                            ),
                          ),
                        )
                      ],
                    ),
                  ],
                )),
            Container(
              height: 10,
            ),
          ],
        ),
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
